﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace ViewMaker.Core.Wpf
{
    public static class CheckedUncheckedBehavior
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CheckedUncheckedBehavior), new PropertyMetadata(CommandCallback));

        public static ICommand GetCommand(ToggleButton obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(ToggleButton obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        private static void CommandCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as ToggleButton;
            if (ele != null)
            {
                if (args.OldValue == null && args.NewValue != null)
                {
                    ele.Checked += new RoutedEventHandler(CheckedUncheckedHandler);
                    ele.Unchecked += new RoutedEventHandler(CheckedUncheckedHandler);
                }
                else if (args.OldValue != null && args.NewValue == null)
                {
                    ele.Checked -= new RoutedEventHandler(CheckedUncheckedHandler);
                    ele.Unchecked -= new RoutedEventHandler(CheckedUncheckedHandler);
                }
            }
        }

        static void CheckedUncheckedHandler(object sender, RoutedEventArgs e)
        {
            var ele = e.OriginalSource as ToggleButton;
            ICommand cmd = (ICommand)ele.GetValue(CommandProperty);
            if (cmd != null) cmd.Execute(null);
        }
    }

}
